package logic

import (
	"context"

	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	"user/internal/svc"
	"user/public"
	"user/user"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录
func (l *UserLoginLogic) UserLogin(in *user.UserLoginRequest) (*user.UserRegisterResponse, error) {
	// todo: add your logic here and delete this line
	//验参
	if in.Mobile == "" {
		return nil, status.Error(codes.FailedPrecondition, "Mobile is required")
	}
	if in.Password == "" {
		return nil, status.Error(codes.FailedPrecondition, "Password is required")
	}

	info := public.User{}
	//查询用户是否存在
	err := public.DB.Table("user").Where("user_mobile=?", in.Mobile).First(&info).Error
	if err != nil {
		return nil, status.Error(codes.InvalidArgument, "search mobile error  or user not find"+err.Error())
	}

	//验证加盐密码
	ok := public.CheckPassword(info.Salt, in.Password, info.UserSaltPassword)
	if !ok {
		return nil, status.Error(codes.InvalidArgument, " Incorrect password")
	}

	//如果已经登录
	if info.UserLoginStatus == 1 {
		return nil, status.Error(codes.InvalidArgument, "The user has already logged in")
	}

	//调用登录方法 修改登录状态
	ok, err = public.UpdateUserLoginStatus(info.UserID, 1)
	if err != nil {
		return nil, status.Error(codes.InvalidArgument, "Update 	user login status failed"+err.Error())
	}

	if !ok {
		return nil, status.Error(codes.InvalidArgument, "update user_login_status error")
	}

	return &user.UserRegisterResponse{
		Data: &user.UserInfo{
			UserId:     info.UserID,
			UserName:   info.UserName,
			UserMobile: info.UserMobile,
		},
	}, nil
}
